package mya.mes.mdc.logic.dispatch.core;

import mya.common.jpa.JPAUtils;
import mya.common.jpa.context.NoLoginLogic;
import mya.common.jpa.context.ServiceContext;
import mya.mes.mdc.local.alarm.MdcAlarmResult;
import mya.mes.mdc.model.alarm.MdcAlarm;
import mya.mes.mdc.queries.alarm.MdcAlarmQuery;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class AlarmCurrent {

    public List<MdcAlarm> cachedUnclosedAlarmList = new ArrayList<>(1024);


    public synchronized List<MdcAlarm> cloneAlarmList() {
        if (cachedUnclosedAlarmList.isEmpty()) {
            return null;
        }
        List<MdcAlarm> list = new ArrayList<>(cachedUnclosedAlarmList.size());
        list.addAll(cachedUnclosedAlarmList);
        return list;
    }

    public synchronized void update(MdcAlarmResult alarmResult) {
        if (alarmResult == null) {
            return;
        }
        if (alarmResult.alarmCreatedList != null) {
            cachedUnclosedAlarmList.addAll(alarmResult.alarmCreatedList);
        }
        if (alarmResult.alarmCloseList != null) {
            Iterator<MdcAlarm> it = cachedUnclosedAlarmList.iterator();
            while (it.hasNext()) {
                MdcAlarm mdcAlarm = it.next();
                for (MdcAlarm stopAlarm : alarmResult.alarmCloseList) {
                    if (mdcAlarm.getObjectId().equals(stopAlarm.getObjectId())) {
                        it.remove();
                        break;
                    }
                }

            }
        }

    }

    public void updateCache() throws Exception {
        List<MdcAlarm> alarmList = loadCurrentAlarm();
        cachedUnclosedAlarmList.clear();
        cachedUnclosedAlarmList.addAll(alarmList);

    }


    public List<MdcAlarm> loadCurrentAlarm(ServiceContext context) throws Exception {
        List<MdcAlarm> tmp = MdcAlarmQuery.loadAll(context);

        return tmp;
    }


    public List<MdcAlarm> loadCurrentAlarm() throws Exception {
        NoLoginLogic logic = new NoLoginLogic(JPAUtils.DEFAULT_TENANT_ID) {
            @Override
            protected Object process(ServiceContext context) throws Exception {
                List<MdcAlarm> tmp = MdcAlarmQuery.loadAll(context);
                return tmp;
            }
        };

        return (List<MdcAlarm>) logic.callLogic();
    }

}
